"use client"

import { useState } from "react"
import { View, Text, StyleSheet, TouchableOpacity, ScrollView, Platform } from "react-native"
import { Volume2, BookmarkIcon, Check, BookOpen } from "lucide-react-native"
import { theme } from "../../constants/theme"
import { useRouter } from "expo-router"

// 单词条目的接口定义
interface VocabularyItem {
    id: string
    word: string
    phonetic: string
    meaning: string
    type: string
    syllables: string[]
    status: "new" | "learning" | "mastered"
    favorite: boolean
}

// 特殊音节颜色映射
const SYLLABLE_COLORS = {
    mu: theme.colors.secondary.orange.default,
    tion: theme.colors.primary.default,
    vor: theme.colors.secondary.orange.default,
    tism: theme.colors.primary.default,
    bine: theme.colors.primary.default,
    ject: theme.colors.primary.default,
    ics: theme.colors.primary.default,
    pli: theme.colors.secondary.orange.default,
    fy: theme.colors.primary.default,
    ti: theme.colors.secondary.orange.default,
    ten: theme.colors.secondary.orange.default,
}

// 状态颜色映射
const STATUS_COLORS = {
    new: "#FF9999",
    learning: "#FF9500",
    mastered: "#99CC99",
}

interface WrongWordsVocabularyListProps {
    vocabularyData: VocabularyItem[]
    activeTab: string
    settings: {
        split: boolean
        fontSize: "small" | "medium" | "large"
    }
    selectedWordId: string | null
    onWordPress: (wordId: string) => void
    onUpdateStatus: (wordId: string, status: "new" | "learning" | "mastered") => void
    onToggleFavorite: (wordId: string) => void
    deleteMode?: boolean
    selectedWords?: string[]
}

export function WrongWordsVocabularyList({
    vocabularyData,
    activeTab,
    settings,
    selectedWordId,
    onWordPress,
    onUpdateStatus,
    onToggleFavorite,
    deleteMode = false,
    selectedWords = [],
}: WrongWordsVocabularyListProps) {
    const router = useRouter()
    const [revealedItems, setRevealedItems] = useState<Record<string, boolean>>({})
    const [isPlaying, setIsPlaying] = useState(false)

    // 根据字号设置获取字体大小
    const getFontSize = () => {
        switch (settings.fontSize) {
            case "small":
                return theme.fontSize.sm
            case "large":
                return theme.fontSize.lg
            case "medium":
            default:
                return theme.fontSize.md
        }
    }

    // 渲染拆分单词
    const renderSplitWord = (word, syllables, fontSize) => {
        return (
            <View style={styles.splitWordContainer}>
                {syllables.map((syllable, index) => (
                    <Text
                        key={index}
                        style={[
                            styles.syllable,
                            {
                                fontSize,
                                color: SYLLABLE_COLORS[syllable] || theme.colors.neutral.black,
                                fontWeight: SYLLABLE_COLORS[syllable] ? theme.fontWeight.bold : theme.fontWeight.semiBold,
                            },
                        ]}
                    >
                        {syllable}
                    </Text>
                ))}
            </View>
        )
    }

    // 临时显示被遮挡的内容
    const toggleReveal = (itemId: string) => {
        setRevealedItems((prev) => ({
            ...prev,
            [itemId]: !prev[itemId],
        }))
    }

    // 模拟播放语音
    const playAudio = (word: string) => {
        if (isPlaying) return

        setIsPlaying(true)

        // 模拟播放音频
        console.log(`播放单词: ${word}`)

        // 2秒后自动关闭播放状态
        setTimeout(() => {
            setIsPlaying(false)
        }, 2000)
    }

    // 如果没有单词，显示空状态
    if (vocabularyData.length === 0) {
        return (
            <View style={styles.emptyContainer}>
                <View style={styles.emptyIconContainer}>
                    <BookOpen size={60} color={theme.colors.primary.light} />
                </View>
                <Text style={styles.emptyTitle}>暂无错词</Text>
                <Text style={styles.emptyDescription}>
                    您目前没有任何错词记录。当您在学习过程中标记单词为错词时，它们将会显示在这里。
                </Text>
                {/* <TouchableOpacity style={styles.emptyButton} onPress={() => router.push("/learning-screen")}>
                    <Text style={styles.emptyButtonText}>去学习</Text>
                </TouchableOpacity> */}
            </View>
        )
    }

    return (
        <ScrollView style={styles.contentContainer} showsVerticalScrollIndicator={false}>
            {vocabularyData.map((item) => (
                <TouchableOpacity
                    key={item.id}
                    style={[
                        styles.wordCard,
                        selectedWordId === item.id && !deleteMode && styles.wordCardSelected,
                        deleteMode && selectedWords.includes(item.id) && styles.wordCardSelectedForDelete,
                    ]}
                    activeOpacity={0.9}
                    onPress={() => onWordPress(item.id)}
                >
                    {deleteMode && (
                        <View style={styles.checkboxContainer}>
                            <View style={[styles.checkbox, selectedWords.includes(item.id) && styles.checkboxSelected]}>
                                {selectedWords.includes(item.id) && <Check size={16} color={theme.colors.neutral.white} />}
                            </View>
                        </View>
                    )}
                    <View style={[styles.wordCardContent, deleteMode && styles.wordCardContentWithCheckbox]}>
                        {/* 左侧：单词部分 */}
                        <View style={styles.wordSection}>
                            <View style={styles.wordContent}>
                                <View style={styles.wordRow}>
                                    {settings.split ? (
                                        renderSplitWord(item.word, item.syllables, getFontSize())
                                    ) : (
                                        <Text style={[styles.word, { fontSize: getFontSize() }]}>{item.word}</Text>
                                    )}

                                   
                                </View>

                                <View style={styles.phoneticRow}>
                                    <Text style={styles.phonetic}>{item.phonetic}</Text>

                                    {/* 音频按钮 - 更小更不显眼 */}
                                    <TouchableOpacity
                                        style={styles.audioButton}
                                        onPress={(e) => {
                                            e.stopPropagation()
                                            playAudio(item.word)
                                        }}
                                        disabled={isPlaying}
                                    >
                                        <Volume2 size={14} color={theme.colors.neutral.gray} />
                                    </TouchableOpacity>
                                </View>
                            </View>

                            {/* 单词遮盖蒙版 */}
                            {activeTab === "words" && !deleteMode && (
                                <TouchableOpacity
                                    style={styles.maskContainer}
                                    onPress={() => toggleReveal(`word-${item.id}`)}
                                    activeOpacity={1}
                                >
                                    {!revealedItems[`word-${item.id}`] && <View style={styles.mask} />}
                                </TouchableOpacity>
                            )}
                        </View>

                        {/* 右侧：翻译部分 */}
                        <View style={styles.meaningSection}>
                            <View style={styles.meaningContainer}>
                                <Text style={styles.type}>{item.type}</Text>
                                <Text style={[styles.meaning, { fontSize: getFontSize() }]}>{item.meaning}</Text>
                            </View>

                            {/* 翻译遮盖蒙版 */}
                            {activeTab === "translation" && !deleteMode && (
                                <TouchableOpacity
                                    style={styles.maskContainer}
                                    onPress={() => toggleReveal(`meaning-${item.id}`)}
                                    activeOpacity={1}
                                >
                                    {!revealedItems[`meaning-${item.id}`] && <View style={styles.mask} />}
                                </TouchableOpacity>
                            )}
                        </View>
                    </View>
                </TouchableOpacity>
            ))}
            <View style={{ height: 20 }} />
        </ScrollView>
    )
}

const styles = StyleSheet.create({
    contentContainer: {
        flex: 1,
        paddingHorizontal: theme.spacing.lg,
    },
    wordCard: {
        backgroundColor: theme.colors.neutral.white,
        borderRadius: theme.borderRadius.large,
        padding: theme.spacing.lg,
        marginBottom: theme.spacing.md,
        borderWidth: 2,
        borderColor: "transparent",
        flexDirection: "row",
        ...Platform.select({
            ios: {
                shadowColor: "rgba(0, 0, 0, 0.1)",
                shadowOffset: { width: 0, height: 2 },
                shadowOpacity: 0.5,
                shadowRadius: 4,
            },
            android: {
                elevation: 4,
            },
        }),
    },
    wordCardSelected: {
        borderColor: theme.colors.primary.default,
        backgroundColor: "#F0F5FF", // 改为实色而非透明色
    },
    wordCardSelectedForDelete: {
        borderColor: theme.colors.secondary.red.default,
        backgroundColor: "#FFF1F1", // 浅红色背景
    },
    wordCardContent: {
        flexDirection: "row",
        justifyContent: "space-between",
        flex: 1,
    },
    wordCardContentWithCheckbox: {
        marginLeft: theme.spacing.md,
    },
    wordSection: {
        flex: 1,
        marginRight: theme.spacing.lg,
        position: "relative",
    },
    wordContent: {
        justifyContent: "center",
    },
    wordRow: {
        flexDirection: "row",
        alignItems: "center",
        marginBottom: theme.spacing.xs,
        position: "relative",
    },
    phoneticRow: {
        flexDirection: "row",
        alignItems: "center",
    },
    audioButton: {
        marginLeft: theme.spacing.sm,
        padding: 2,
    },
    statusIndicator: {
        width: 8,
        height: 8,
        borderRadius: 4,
        marginLeft: theme.spacing.sm,
    },
    favoriteIndicator: {
        marginLeft: theme.spacing.xs,
    },
    meaningSection: {
        flex: 1.5,
        position: "relative",
    },
    word: {
        fontSize: theme.fontSize.lg,
        fontWeight: theme.fontWeight.semiBold,
        color: theme.colors.neutral.black,
        flex: 1,
    },
    splitWordContainer: {
        flexDirection: "row",
        flexWrap: "wrap",
        flex: 1,
    },
    syllable: {
        marginRight: 2,
        fontWeight: theme.fontWeight.semiBold,
    },
    phonetic: {
        fontSize: theme.fontSize.sm,
        color: theme.colors.neutral.gray,
        fontFamily: "System",
    },
    meaningContainer: {
        flexDirection: "row",
        alignItems: "flex-start",
        flexWrap: "wrap",
    },
    type: {
        fontSize: theme.fontSize.sm,
        color: theme.colors.primary.default,
        fontWeight: theme.fontWeight.semiBold,
        marginRight: theme.spacing.sm,
        marginTop: 2, // 稍微调整一下垂直对齐
    },
    meaning: {
        fontSize: theme.fontSize.md,
        color: theme.colors.neutral.darkGray,
        flex: 1,
    },
    // 详情按钮样式
    detailsButton: {
        flexDirection: "row",
        alignItems: "center",
        backgroundColor: "rgba(91, 142, 244, 0.1)",
        paddingVertical: 2,
        paddingHorizontal: 6,
        borderRadius: theme.borderRadius.small,
        marginLeft: theme.spacing.sm,
    },
    detailsText: {
        fontSize: 10,
        color: theme.colors.primary.default,
    },
    maskContainer: {
        position: "absolute",
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        zIndex: 10,
    },
    mask: {
        position: "absolute",
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        backgroundColor: "#E9E9E9", // 使用实心灰色，不使用透明度
        borderRadius: 4,
        zIndex: 20, // 增加z-index确保在最上层
    },
    checkboxContainer: {
        justifyContent: "center",
        marginRight: theme.spacing.sm,
    },
    checkbox: {
        width: 24,
        height: 24,
        borderRadius: 12,
        borderWidth: 2,
        borderColor: theme.colors.neutral.lightGray,
        alignItems: "center",
        justifyContent: "center",
    },
    checkboxSelected: {
        backgroundColor: theme.colors.secondary.red.default,
        borderColor: theme.colors.secondary.red.default,
    },
    // 空状态样式
    emptyContainer: {
        flex: 1,
        alignItems: "center",
        justifyContent: "center",
        paddingHorizontal: theme.spacing.xl,
    },
    emptyIconContainer: {
        width: 120,
        height: 120,
        borderRadius: 60,
        backgroundColor: "rgba(91, 142, 244, 0.1)",
        alignItems: "center",
        justifyContent: "center",
        marginBottom: theme.spacing.lg,
    },
    emptyTitle: {
        fontSize: theme.fontSize.xl,
        fontWeight: theme.fontWeight.bold,
        color: theme.colors.neutral.black,
        marginBottom: theme.spacing.md,
    },
    emptyDescription: {
        fontSize: theme.fontSize.md,
        color: theme.colors.neutral.gray,
        textAlign: "center",
        marginBottom: theme.spacing.xl,
        lineHeight: 22,
    },
    emptyButton: {
        backgroundColor: theme.colors.primary.default,
        paddingHorizontal: theme.spacing.xl,
        paddingVertical: theme.spacing.md,
        borderRadius: theme.borderRadius.large,
    },
    emptyButtonText: {
        color: theme.colors.neutral.white,
        fontSize: theme.fontSize.md,
        fontWeight: theme.fontWeight.semiBold,
    },
})

